﻿using System;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using PAMD.Business.Models;
using PAMD.Controllers.Helper;
using PAMD.Database.Services;
using System.Web.Security;
using System.Web;
using PAMD.Database;

namespace PAMD.Controllers.Account
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class AccountController : Controller
    {
        [Import(typeof(AccountService))]
        private AccountService RegService { get; set; }

        public ActionResult ActivateAccount(string q)
        {
            var activationKey = q;
            var success = RegService.ActivateRegisteredUser(activationKey);
            if (success)
            {
                return View();
            }
            return View("ReSendActivation");
        }

        public ActionResult Login(LoginModel loginModel)
        {
            if (ValidationHelper.ValidateLogin(loginModel))
            {
                UserDetail userDetail = RegService.Login(loginModel.Email, loginModel.Password);
                if (userDetail != null)
                {
                    string cookiestr;
                    var ticket = new FormsAuthenticationTicket(1, userDetail.FirstName, DateTime.Now, DateTime.Now.AddMinutes(30), loginModel.KeepSign, loginModel.Email);
                    cookiestr = FormsAuthentication.Encrypt(ticket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                    if (loginModel.KeepSign)
                        cookie.Expires = ticket.Expiration;
                    cookie.Path = FormsAuthentication.FormsCookiePath;
                    Response.Cookies.Add(cookie);

                    string strRedirect;
                    strRedirect = Request["ReturnUrl"];
                    if (strRedirect == null)
                        return RedirectToAction("Index", "Home");

                    return Redirect(strRedirect);
                }
                ViewData.ModelState.AddModelError(string.Empty, "Invalid");
                return View();
            }
            return View();
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ReSendActivation(RegistrationModel model)
        {
            string host = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
            var success = RegService.ResendActivationEmail(model.Email, host);
            if (success)
            {
                return View("ActivationEmailSent", model);
            }
            return View("ErrorSendActivation");
        }

        public ActionResult ForgotPassword(LoginModel model)
        {
            if (Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("ForgotPassword");
            }
            return View();
        }

        public ActionResult ResetPassword(LoginModel model)
        {
            string host = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
            if (RegService.ResetPassword(model.Email, host) != null)
            {
                return View("ResetPasswordEmailSent");
            }
            ViewData.ModelState.AddModelError(string.Empty, "Invalid");
            return View("ForgotPassword");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult RecoverPassword(string q)
        {
            ResetPasswordModel model = new ResetPasswordModel();
            var user = RegService.UserDetailByResetKey(q);
            if (user == null)
            {
                ViewData.ModelState.AddModelError(string.Empty, "Invalid");
                return View();
            }

            model.Email = user.Email;
            model.ResetKey = q;
            return View(model);
        }

        public ActionResult RecoverPassword(ResetPasswordModel model)
        {
            RegService.UpdateUserPassword(model.ResetKey, model.Password);
            return View("PasswordChanged");
        }
    }
}